import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { Form, Select, DatePicker, Table, InputNumber, Icon } from 'antd'
import moment from 'moment'
import locale from 'antd/lib/date-picker/locale/zh_CN'
import zh from 'moment/locale/zh-cn'
import { findAround, findFarmlandWeather, copyFarmlandWeather } from 'utils/Api'
import { toast } from 'react-toastify'
moment.locale('zh')

function isNumber(value) {
  return typeof value == 'number'
}

const {Option} = Select
class Forms extends Component {
  constructor(props) {
    super(props)
    this.state = {
      startDate: moment().subtract(29, 'days'),
      endDate: moment(),
      options: [],
      source: null,
      changed: [],
      pending: false
    }
  }
  inputChange = (row, name, value) => {
    if (typeof value !== 'number' && isNaN(value)) {
      console.log(value)
      if (typeof value === 'undefined') {
        return
      }
      toast.error('输入格式不正确')
      return
    }
    const { source, changed } = this.state
    if (row.key % 2 === 1) {
      const filter = source.filter(s => s.id === name)[0]
      filter.pcpn = value
      const changedFilter = changed.filter(c => c.id === filter.id)
      changedFilter.length === 0 && changed.push(filter)
      changedFilter.length !== 0 && (changedFilter.pcpn = value)
      this.setState({
        source
      })
    } else {
      const filter = source.filter(s => s.id === name)[0]
      filter.irrigation = value
      const changedFilter = changed.filter(c => c.id === filter.id)
      changedFilter.length === 0 && changed.push(filter)
      changedFilter.length !== 0 && (changedFilter.irrigation = value)
      this.setState({
        source
      })
    }
  }
  handleData = (farmlandWeatherView) => {
    if (!farmlandWeatherView) {
      return []
    }
    const columns = farmlandWeatherView.map(fwv => ({
      title: fwv.date,
      dataIndex: fwv.id,
      key: fwv.id,
      render: (value, row, index) => {
        return <InputNumber
          min={0} step={0.01}
          // className={Number(value).toString() !== value ? 'input-error' : ''}
          name={fwv.id}
          value={value} onChange={this.inputChange.bind(this, row, fwv.id)} />
      }
    }))
    // dates.slice(0, 10)
    const dataSourcesItem1 = { key: 1 }
    const dataSourcesItem2 = { key: 2 }
    for (let i = 0; i < 10; i++) {
      dataSourcesItem1[farmlandWeatherView[i].id] = farmlandWeatherView[i].pcpn || ''
      dataSourcesItem2[farmlandWeatherView[i].id] = farmlandWeatherView[i].irrigation || ''
    }
    const dataSourcesItem3 = { key: 3 }
    const dataSourcesItem4 = { key: 4 }
    for (let i = 10; i < 20; i++) {
      dataSourcesItem3[farmlandWeatherView[i].id] = farmlandWeatherView[i].pcpn || ''
      dataSourcesItem4[farmlandWeatherView[i].id] = farmlandWeatherView[i].irrigation || ''
    }
    const dataSourcesItem5 = { key: 5 }
    const dataSourcesItem6 = { key: 6 }
    for (let i = 20; i < 30; i++) {
      dataSourcesItem5[farmlandWeatherView[i].id] = farmlandWeatherView[i].pcpn || ''
      dataSourcesItem6[farmlandWeatherView[i].id] = farmlandWeatherView[i].irrigation || ''
    }
    return [
      columns,
      [
        dataSourcesItem1, dataSourcesItem2
      ],
      [
        dataSourcesItem3, dataSourcesItem4
      ],
      [
        dataSourcesItem5, dataSourcesItem6
      ],
    ]

  }
  componentDidMount() {
    const { landId } = this.props
    this.update()
    findAround({landId})
      .then(({msg, result}) => {
        if (msg === '200') {
          this.setState({
            options: result || []
          })
        }
      })
  }
  getItemsValue = () => {
    const { error, changed } = this.state
    if (error) {
      toast.error('输入内容有误，请重新输入')
      return null
    }
    return changed
  }

  handleChange = (value) => {
    const { landId } = this.props
    const { startDate, endDate } = this.state
    this.setState({
      pending: true
    })
    const fd = new FormData()
    fd.append('landId', value)
    fd.append('targetLandId', landId)
    fd.append('startDate', startDate.format('YYYY/MM/DD'))
    fd.append('endDate', endDate.format('YYYY/MM/DD'))
    copyFarmlandWeather(fd)
      .then(({msg, result}) => {
        if (msg === '200') {
          this.setState({
            source: result || [],
            pending: false,
          })
        }
      })
  }
  componentDidUpdate(prevProps, prevState) {
    const { startDate, endDate } = this.state
    if (!prevState.startDate.isSame(startDate) || !prevState.endDate.isSame(endDate)) {
      this.update()
      return
    }
  }
  update = () => {
    const { landId } = this.props
    const { startDate, endDate } = this.state
    this.setState({
      pending: true
    })
    findFarmlandWeather({
      landId,
      startDate: startDate.format('YYYY/MM/DD'),
      endDate: endDate.format('YYYY/MM/DD')
    })
      .then(({msg,result}) => {
        if (msg === '200') {
          this.setState({
            source: result,
            pending: false
          })
        }
      })
  }
  onStartChange = (date, dateString) => {
    if (!date) {
      return
    }
    this.setState({
      startDate: date,
      endDate: moment(new Date(dateString)).add(29, 'days')
    })
  }
  onEndChange = (date, dateString) => {
    if (!date) {
      return
    }
    this.setState({
      startDate: moment(new Date(dateString)).subtract(29, 'days'),
      endDate: date,
    })
  }
  disabledStartDate = (current) => {
    return current.valueOf() > moment().subtract(29, 'days').valueOf()
  }
  disabledEndDate = (current) => {
    return current.valueOf() > moment().valueOf()
  }
  render() {
    const { startDate, endDate, options, pending, source } = this.state
    const [columns, dataSource1, dataSource2, dataSource3] = this.handleData(source)

    return (
      <Form>
        <div className='filter'>
          <div className='datapicker'>
            <DatePicker
              disabledDate={this.disabledStartDate}
              format="YYYY/MM/DD"
              value={startDate}
              placeholder="起始时间"
              onChange={this.onStartChange}
              locale={locale}
            // onOpenChange={this.handleStartOpenChange}
            />
            <DatePicker
              disabledDate={this.disabledEndDate}
              format="YYYY/MM/DD"
              locale={locale}
              value={endDate}
              placeholder="终止时间"
              onChange={this.onEndChange}
            />
          </div>
          <div className='drop-down'>
            <Select 
              placeholder="从附近田地读取"
              onChange={this.handleChange} notFoundContent='无数据' >
              {options.map(option => 
                <Option key={option.id}>{option.name}</Option>)}
            </Select>
          </div>
        </div>
        <div className='content'>
          {pending && <div className='icon-loading'>
            <Icon type="loading" theme="outlined" />
          </div>}
          {columns && <div className='table'>
            
            <Table
              bordered
              dataSource={dataSource1}
              columns={[
                {
                  key: -1,
                  dataIndex: -1,
                  title: '',
                  render: function (value, row, index) {
                    if (row.key % 2 === 0) {
                      return '灌溉量'
                    } else {
                      return '降雨量'
                    }
                  }
                },
                ...(columns && columns.slice(0, 10))
              ]}
              pagination={false}
            />
            <Table
              bordered
              dataSource={dataSource2}
              columns={[
                {
                  key: -1,
                  dataIndex: -1,
                  title: '',
                  render: function (value, row, index) {
                    if (row.key % 2 === 0) {
                      return '灌溉量'
                    } else {
                      return '降雨量'
                    }
                  }
                },
                ...(columns && columns.slice(10, 20))
              ]}
              pagination={false}
            />
            <Table
              bordered
              dataSource={dataSource3}
              columns={[
                {
                  key: -1,
                  dataIndex: -1,
                  title: '',
                  render: function (value, row, index) {
                    if (row.key % 2 === 0) {
                      return '灌溉量'
                    } else {
                      return '降雨量'
                    }
                  }
                },
                ...columns.slice(20)
              ]}
              pagination={false}
            />
          </div>}
        </div>
        
      </Form>
    )
  }
}
Forms.propTypes = {
  landId: PropTypes.string,
  startDate: PropTypes.object,
  endDate: PropTypes.object,
  res: PropTypes.object,
}
export default Forms